/*


Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controllers

import (
	"context"
	"github.com/go-logr/logr"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/intstr"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

	appsv1 "k8s.io/api/apps/v1"
	coresv1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	appv1alpha1 "github.com/genfanh/nginx-operator-demo/api/v1alpha1"
)

// NginxReconciler reconciles a Nginx object
type NginxReconciler struct {
	client.Client
	Log    logr.Logger
	Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups=app.nginx.hancf.com,resources=nginxes,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=app.nginx.hancf.com,resources=nginxes/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list
// +kubebuilder:rbac:groups=core,resources=services,verbs=get;list;watch;create;update;patch;delete

func (r *NginxReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
	_ = context.Background()
	_ = r.Log.WithValues("nginx", req.NamespacedName)

	// your logic here
	// 获取app实例
	app := &appv1alpha1.Nginx{}
	err := r.Get(context.TODO(), req.NamespacedName, app)
	if err != nil {
		if errors.IsNotFound(err) {
			return ctrl.Result{}, nil
		}
		return ctrl.Result{}, err
	}
	// 查看 deployment是否存在， 不存在则创建
	dep := &appsv1.Deployment{}
	err = r.Get(context.TODO(), types.NamespacedName{Name: app.Name, Namespace: app.Namespace}, dep)
	if err != nil {
		if errors.IsNotFound(err) {
			newDep := r.deploymentForApp(app)
			if err = r.Create(context.TODO(), newDep); err != nil {
				return ctrl.Result{}, err
			}
			r.Log.Info("deployment 添加")
			return ctrl.Result{Requeue: true}, nil
		} else {
			return ctrl.Result{}, err
		}
	}
	// Ensure the deployment size is the same as the spec.
	size := app.Spec.Size
	if *dep.Spec.Replicas != size {
		dep.Spec.Replicas = &size
		if err = r.Update(context.TODO(), dep); err != nil {
			return ctrl.Result{}, err
		}
		return ctrl.Result{Requeue: true}, nil
	}

	// Update the App status with the pod names.
	// List the pods for this app's deployment.
	podList := &coresv1.PodList{}
	listOpts := []client.ListOption{
		client.InNamespace(app.Namespace),
		client.MatchingLabels(labelsForApp(app.Name)),
	}
	if err = r.List(context.TODO(), podList, listOpts...); err != nil {
		return ctrl.Result{}, err
	}

	// 创建 service
	svc := &coresv1.Service{}
	err = r.Get(context.TODO(), types.NamespacedName{Name: app.Name + "-svc", Namespace: app.Namespace}, svc)
	if err != nil {
		if errors.IsNotFound(err) {
			r.Log.Info("未找到 svc ")
			newSvc := r.serviceForApp(app)
			if err = r.Create(context.TODO(), newSvc); err != nil {
				return ctrl.Result{}, err
			}
			r.Log.Info("service 已经创建")
			return ctrl.Result{}, nil
		} else {
			return ctrl.Result{}, err
		}
	}

	// 更新状态
	app.Status.Status = "Running"
	err = r.Status().Update(context.TODO(), app)
	if err != nil {
		r.Log.Info("Status更新失败")
		return ctrl.Result{}, err
	}
	return ctrl.Result{}, nil
}

// 返回 Nginx 对应的 一个 Deployment 对象
func (r *NginxReconciler) deploymentForApp(m *appv1alpha1.Nginx) *appsv1.Deployment {
	labels := labelsForApp(m.Name)

	replicas := m.Spec.Size
	image := m.Spec.Image

	dep := &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      m.Name,
			Namespace: m.Namespace,
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: &replicas,
			Selector: &metav1.LabelSelector{
				MatchLabels: labels,
			},
			Template: coresv1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: labels,
				},
				Spec: coresv1.PodSpec{
					Containers: []coresv1.Container{
						{
							Image: image,
							Name:  "nginx",
							Ports: []coresv1.ContainerPort{
								{
									ContainerPort: 80,
									Name:          "http",
								},
							},
						},
					},
				},
			},
		},
	}
	// 设置 app 实例为 Deployment的 所有者和 controller
	controllerutil.SetControllerReference(m, dep, r.Scheme)
	return dep
}

// 返回 Nginx 对应的 service 对象
func (r *NginxReconciler) serviceForApp(m *appv1alpha1.Nginx) *coresv1.Service {
	labels := labelsForApp(m.Name)

	svc := &coresv1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      m.Name + "-svc",
			Namespace: m.Namespace,
		},
		Spec: coresv1.ServiceSpec{
			Selector: labels,
			Type:     "NodePort",
			Ports: []coresv1.ServicePort{
				{
					Name: "http",
					Port: 80,
					TargetPort: intstr.IntOrString{
						IntVal: 80,
					},
				},
			},
		},
	}
	// 设置 app 实例为 Deployment的 所有者和 controller
	err := controllerutil.SetControllerReference(m, svc, r.Scheme)
	if err != nil {
		r.Log.Error(err, "设置 svc 为 nignx 的svc 失败")
	}
	return svc
}

// labelsForApp creates a simple set of labels for App.
func labelsForApp(name string) map[string]string {
	return map[string]string{"app_name": "nginx", "app_cr": name}
}

func (r *NginxReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&appv1alpha1.Nginx{}).
		Owns(&appsv1.Deployment{}).
		Owns(&coresv1.Service{}).
		Complete(r)
}
